var util = require('../../utils/util.js')
var md5 = require('../../utils/md5.js')

// var talkUrl = "https://talk.leautolink.com";
// var radioUrl = "https://radio.leautolink.com";

var talkUrl = "https://talk.airmmi.com";
var radioUrl = "https://radio.airmmi.com";

const app = getApp()

const backgroundAudioManager = wx.getBackgroundAudioManager();
const lazy = 100;

Page({
  onLoad: function (options) {
    // console.info(options);

    var _this = this;

    wx.getStorage({
      key: 'audios',
      success: function (res) {
        // console.log(res.data)
        _this.setData({
          audios: res.data.audios
        })
      }
    })

    var currentPlay = wx.getStorageSync('currentPlay');

    var index = parseInt(currentPlay.index);
    var audio = currentPlay.audio;

    if (options.reOpen == "true") {
      audio['reOpen'] = true;
    }

    if (audio.playUrl) {
      _this.selectAudio(audio, index);
    } else {
      if (!_this.data.audios) {
        var int = setInterval(function () {
          if (_this.data.audios) {
            clearInterval(int);
            _this.selectAudio(audio, index);
          }
        }, lazy);
      } else {
        _this.selectAudio(audio, index);
      }
    }

    backgroundAudioManager.onTimeUpdate(function (callback) {
      if (_this.seeking == false) {
        _this.setData({
          slider_value: backgroundAudioManager.currentTime,
          play_start: util.formatTime(backgroundAudioManager.currentTime)
        })
      }
    });

    backgroundAudioManager.onEnded(function (callback) {
      if (_this.data.ordering) {
        var index = _this.data.index + 1;
        if (_this.data.audios.length <= index) {
          index = 0;
        }
      } else {
        var index = Math.floor(Math.random() * _this.data.audios.length);
      }

      var audio = _this.data.audios[index];

      _this.playUrl(audio, index);
    });

    backgroundAudioManager.onPrev(function (callback) {
      _this.prev();
    });

    backgroundAudioManager.onNext(function (callback) {
      _this.next();
    });

    backgroundAudioManager.onCanplay(function (callback) {
      // console.info("onCanplay：" + callback);
      _this.hideNavigationBarLoading();
    });

    backgroundAudioManager.onWaiting(function (callback) {
      // console.info("onWaiting：" + callback);
      _this.showNavigationBarLoading();
    });
  },

  showNavigationBarLoading: function () {
    wx.showNavigationBarLoading()
  },

  hideNavigationBarLoading: function () {
    wx.hideNavigationBarLoading()
  },

  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: '说出你想听的，我都会满足你！',
      path: 'pages/index/index',
      imageUrl: talkUrl + '/images/share.jpg',
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },

  prev_click: function () {
    this.setData({
      prev: '/images/prev_click.png'
    });
  },
  next_click: function () {
    this.setData({
      next: '/images/next_click.png'
    });
  },
  list_click: function () {
    this.setData({
      list: '/images/list_click.png'
    });
  },
  play_pause_click: function () {
    if (backgroundAudioManager.paused) {
      this.setData({
        play_pause: '/images/play_click.png'
      })
    } else {
      this.setData({
        play_pause: '/images/pause_click.png'
      })
    }
  },
  order_random_click: function () {
    if (this.data.ordering) {
      this.setData({
        order_random: '/images/order_click.png',
      })
    } else {
      this.setData({
        order_random: '/images/random_click.png',
      })
    }
  },

  list: function () {
    var _this = this;
    setTimeout(function () {
      _this.setData({
        list: '/images/list.png'
      });
    }, lazy);
  },

  prev: function () {
    var _this = this;

    setTimeout(function () {
      _this.setData({
        prev: '/images/prev.png'
      });
    }, lazy);


    var index = parseInt(_this.data.index) - 1;
    if (index < 0) {
      index = _this.data.audios.length - 1;
    }
    var audio = _this.data.audios[index];

    _this.playUrl(audio, index);
  },

  next: function () {
    var _this = this;

    setTimeout(function () {
      _this.setData({
        next: '/images/next.png'
      });
    }, lazy);

    var index = parseInt(_this.data.index) + 1;
    if (_this.data.audios.length <= index) {
      index = 0;
    }

    var audio = _this.data.audios[index];

    _this.playUrl(audio, index);
  },

  selectAudio: function (audio, index) {
    if (!audio.playUrl) {
      wx.showToast({
        title: "由于版权限制，无法播放",
        icon: "none"
      })
      this.setData({
        index: index,
      });

      this.next();
      return;
    }

    var _this = this;
    var name = "";

    backgroundAudioManager.title = audio.name
    backgroundAudioManager.epname = audio.name
    backgroundAudioManager.singer = audio.author;
    if (!audio.image){
      audio.image = talkUrl + "/images/story.jpg"
    }
    backgroundAudioManager.coverImgUrl = audio.image;

    //如果是从主要点击图片进来的话，不需要再重新播放。
    if (audio.reOpen) {
      if (backgroundAudioManager.paused) {
        backgroundAudioManager.play();
      }
    } else{
      // 设置了 src 之后会自动播放
      backgroundAudioManager.src = audio.playUrl
      // this.showNavigationBarLoading();
    }

    // console.info("audio.duration:" + audio.duration);

    if (!audio.duration) {
      audio.duration = 0;
    }

    this.setData({
      index: index,
      poster: audio.image,
      duration: audio.duration / 1000,
      name: audio.name,
      author: audio.author,
      play_end: util.formatTime(audio.duration / 1000)
    })

    var pages = getCurrentPages();
    pages[0].showPlayImage(audio.image);
    // console.info(pages);

    wx.setStorage({
      key: "currentPlay",
      data: {
        audio: audio,
        index: index
      }
    })

    // 有些数据没有duration，但是可以从播放器中获取backgroundAudioManager.duration
    if (audio.live != "1" && !audio.duration) {
      var int = setInterval(function () {
        if (backgroundAudioManager.duration) {
          clearInterval(int);
          _this.setData({
            duration: backgroundAudioManager.duration,
            play_end: util.formatTime(backgroundAudioManager.duration)
          })
        }
      }, lazy);
    }

    wx.setNavigationBarTitle({
      title: audio.name
    })
  },

  data: {
    index: 0,
    playing: true,
    ordering: true,
    play_start: "00:00",
    prev: '/images/prev.png',
    next: '/images/next.png',
    list: '/images/list.png',
    play_pause: '/images/pause.png',
    order_random: '/images/order.png',
  },

  play_pause: function (res) {

    var _this = this;

    var play_pause, playing;

    if (backgroundAudioManager.paused) {
      playing = true;
      play_pause = '/images/pause.png'
      backgroundAudioManager.play();

    } else {
      playing = false;
      play_pause = '/images/play.png'
      backgroundAudioManager.pause();
    }

    setTimeout(function () {
      _this.setData({
        playing: playing,
        play_pause: play_pause
      })
    }, lazy);
  },

  order_random: function () {
    var _this = this;
    var ordering, order_random;

    if (this.data.ordering) {
      ordering = false;
      order_random = '/images/random.png';
    } else {
      ordering = true;
      order_random = '/images/order.png';
    }

    setTimeout(function () {
      _this.setData({
        ordering: ordering,
        order_random: order_random
      })
    }, lazy);
  },

  seek: function (e) {
    this.seeking = false;
    // console.info("seek" + e.detail.value);
    backgroundAudioManager.seek(e.detail.value);
  },

  pickerChange: function (e) {
    var index = parseInt(e.detail.value);
    // console.log('picker发送选择改变，携带值为', index)
    var audio = this.data.audios[index];

    this.playUrl(audio, index);
  },

  playUrl: function (audio, index) {

    if (audio.playUrl) {
      this.selectAudio(audio, index);
      return;
    }

    var _this = this;
    var playType = 1;
    if (audio.source && audio.source.sourceType == 'Xiami') {
      playType = 2;
    }

    var header = this.createHeader();

    var str = "mediaId=" + audio.mediaId + "&noncestr=" + header.noncestr + "&playType=" + playType + "&platform=" + header.platform + "&timestamp=" + header.timestamp + "&uid=" + header.uid + "&appkey=" + app.appkey;

    var sign = md5.hex_md5(str);
    header['sign'] = sign;

    wx.request({
      url: radioUrl + '/api/v2/audio/play/get.json',
      data: {
        mediaId: audio.mediaId,
        playType: playType
      },

      header: header,

      method: 'GET',
      success: function (res) {
        // console.log(res.data)

        if (res.data.code != 10000) {
          // console.error(res.data.msg);
          _this.selectAudio(audio, index);
          return;
        }

        var resultData = res.data.data;
        audio.playUrl = resultData.playUrl;

        _this.selectAudio(audio, index);
      }
    })
  },

  sliderSeeking: function () {
    this.seeking = true
    // console.info("seeking");
  },

  seeking: false,

  createHeader: function () {
    return {
      'timestamp': Date.now(),
      'noncestr': util.guid(),
      'uid': app.userId,
      'platform': app.platform
    }
  }
})
